﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;

namespace ClientTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private List<TcpClient> _clients;

        private void NewClient(object client)
        {
            TcpClient cli = (client as TcpClient);
            byte[] buffer = new byte[255];
            cli.Connect("192.168.1.32", 1111);
            try
            {
                while (true)
                {
                    NetworkStream stream = cli.GetStream();
                    buffer = Encoding.ASCII.GetBytes(textBox1.Text);
                    if (buffer[0] == 0)
                        return;
                    stream.Write(buffer, 0, buffer.Length);
                    stream.Flush();
                    stream.Read(buffer, 0, buffer.Length);
                    WriteToLog(string.Join("", buffer));
                }
            }
            finally
            {
                cli.Close();
            }
        }

        void WriteToLog(string message)
        {
            if (listBox1.InvokeRequired)
            {
                listBox1.BeginInvoke(new Action<string>((s)
                    => listBox1.Items.Add(s)), message);
            }
            else
            {
                listBox1.Items.Add(message);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            TcpClient cli = new TcpClient();
            _clients.Add(cli);
            Thread thread = new Thread(NewClient);
            thread.IsBackground = true;
            thread.Start(cli);
        }
    }
}
